<?php
namespace quote\action;

use herosphp\bean\Beans;
use herosphp\core\Controller;
use herosphp\core\Loader;
use herosphp\http\HttpRequest;
use api\utils\WeiXinApi;
use herosphp\core\Log;
use api\utils\SaasApiClient;

/**
 * 微信公众号接口入口
 * @author yu
 */
class WxInitAction extends CommonAction
{
    private $weiXinApi;

    public function __construct()
    {
        $this->weiXinApi = new WeiXinApi();
    }

    public function getWeiXinApi()
    {

        return $this->weiXinApi;
    }

    public function index(HttpRequest $request)
    {


        $weiXinApi = $this->getWeiXinApi();


        //验证 signature , option
        /*
        $echoStr = $_GET["echostr"];

        $token = "monda321654987";

        if ($weiXinApi->checkSignature($token)) {
            echo $echoStr;
            exit;
        }*/

        //处理消息回复

        $postObj = $weiXinApi->getRequestObj();

        if (!empty($postObj)) {

            $RX_TYPE = trim($postObj->MsgType);

            switch ($RX_TYPE) {
                case "text":
                    $resultStr = $this->handleText($postObj);
                    break;
                case "event":
                    $resultStr = $this->handleEvent($postObj);
                    break;
                default:
                    $resultStr = "Unknow msg type: " . $RX_TYPE;
                    break;
            }
            echo $resultStr;
        } else {
            echo "";
        }

        die;
    }

    //处理文字消息
    private function handleText($object)
    {
        $weiXinApi = $this->getWeiXinApi();

        $keyword = trim($object->Content);

        if (empty($keyword)) {

            echo "请输入点儿什么...";
        }

        $quoteDataService = Beans::get('quote.data.service');
        $quoteService = Beans::get('quote.quote.service');
        $usprService = Beans::get('quote.uspr.service');
        $usbrService = Beans::get('quote.usbr.service');

        //添加获取记录
        $openid = $object->FromUserName;//获取用户的openid

        //新建saas会员
        Log::info("开始 执行 api/user/createUserByWeiXin");

        //用微信授权登录后的openid，来向saas中心发起创建saas会员，如果存在则返回查询会员
        $url = "api/user/createUserByWeiXin";

        Log::info("开始 传递 " . $openid);

        $result = SaasApiClient::send($url, array('wx_id' => "$openid"));

        $result_str = serialize($result);

        Log::info("接口返回数据： {$result_str}");

        if (!$result->isSucess()) {

            return false;
        }

        $user = $result->getData();

        $saas_user_id = $user['id'];

        //判断关键词是品名、牌号、品名+牌号、其他，中一种
        if (strpos($keyword, ' ') !== false) {
            $arr = explode(' ', $keyword);
            $k1 = $arr[0];
            $k2 = $arr[1];

        } else {
            $k1 = $keyword;
            $k2 = '';
        }

        //搜索saas牌号库
        $result = $quoteDataService->searchPBFromBrand($k1, $k2);

        //关键词啥都没匹配上
        if ($result['product'] == '' && $result['brand'] == '') {

            $contentStr = getSetting('weixin_auto_reply');

            return $weiXinApi->responseText($object, $contentStr);
        }

        //关键词匹配上牌号库数据，并做搜索记录插入

        $is_find_today_push_content = false;
        $is_find_last_push_content = false;
        $quote = array();
        if ($result['product'] != '' && $result['brand'] != '') {

            $usprService->addRecord($saas_user_id, $result['product']);
            $usbrService->addRecord($saas_user_id, $result['brand']);

            //尝试获取今天的行情数据
            if ($quote = $quoteService->getTodayQuoteByBrand($result['brand'])) {

                $is_find_today_push_content = true;
            }

            if ($quote = $quoteService->getLastQuoteByBrand($result['brand'])) {

                $is_find_last_push_content = true;
            }


        } elseif ($result['product'] != '') {

            $usprService->addRecord($saas_user_id, $result['product']);

            //尝试获取今天的行情数据
            if ($quote = $quoteService->getTodayQuote($result['product'])) {

                $is_find_today_push_content = true;
            }

            if ($quote = $quoteService->getLastQuote($result['product'])) {

                $is_find_last_push_content = true;
            }

        } elseif ($result['brand'] != '') {

            $usbrService->addRecord($saas_user_id, $result['brand']);
            //尝试获取今天的行情数据
            if ($quote = $quoteService->getTodayQuoteByBrand($result['brand'])) {

                $is_find_today_push_content = true;
            }

            if ($quote = $quoteService->getLastQuoteByBrand($result['brand'])) {

                $is_find_last_push_content = true;
            }

        }

        //如果没有今天数据，就尝试找最新数据
        if (!$is_find_today_push_content) {

            if ($is_find_last_push_content) {

                return $weiXinApi->responseText($object, '客官，您要获取的报价数据小塑正在计算，会在每天十点左右更新，请稍等哒！');
            } else {

                return $weiXinApi->responseText($object, '客官，您要获取的报价数据系统暂时没有，小塑会继续努力，帮您达成！');

            }
        }

        $title = $quoteService->getQuoteTitle($quote['adddate'], $quote['product_name']);

        $description = '';

        if($quote['surface_image']==''){

            $picurl = getConfig('site_url') . '/res/quote/img/hq.png';

        }else{

            $picurl = getConfig('site_url') . $quote['surface_image'];

        }

        if ($result['brand'] != '') {

            $url = getConfig('site_url') . '/quote/quote/brand?brand_name=' . $result['brand'] . '&date=' . $quote['adddate'];

        } else {

            if ($result['product'] != '') {

                $url = getConfig('site_url') . '/quote/quote/product?product_name=' . $result['product'] . '&date=' . $quote['adddate'];

            }
        }

        return $weiXinApi->responseOneImageText($object, $title, $description, $picurl, $url);
    }

    //处理事件消息
    private function handleEvent($object)
    {
        $weiXinApi = $this->getWeiXinApi();


        switch ($object->Event) {
            //订阅事件
            case "subscribe":
                $contentStr = getSetting('weixin_auto_reply_added');
                break;
            default :
                $contentStr = "Unknow Event: " . $object->Event;
                break;
        }

        return $weiXinApi->responseText($object, $contentStr);
    }


    public function createMenu()
    {

        $weixin_config = getConfig('weixin_config');


        //获取token
        $weiXinApi = new WeiXinApi();

        $token = $weiXinApi->getAccessToken($weixin_config['appid'], $weixin_config['appser']);

        echo $token;


        //测试删除菜单
        $weiXinApi->delmenu($token);

        $data = '{
           "button":[
           {
                "type":"view",
                 "name":"塑料报价",
                 "url":"http://bj.offer.dasu123.com/mobadmin/offer/add"
            }]
';
        /*
         * ,
            {
                "type":"view",
                 "name":"历史报价单",
                 "url":"http://bj.offer.dasu123.com/mobadmin/offer/index"
             },
             {
                "type":"view",
                 "name":"我的",
                 "url":"http://bj.offer.dasu123.com/mobadmin/index/index"
             }
         */
        //测试创建菜单
        $weiXinApi->creatMenu($token, $data);

        die();
    }


}
